#include <seeta/CStruct.h>
#include "faceobject.h"
#include <QDebug>
#include "global_config.h"


FaceObject::FaceObject(QObject *parent) : QObject(parent)
{
    //初始化引擎
    seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
    int id = 0;


#if 0   //可能是这里路径不对，导致无法初始化，最终导致程序崩溃
    seeta::ModelSetting FD_model("./seeta_models/fd_2_00.dat", device, id );
    seeta::ModelSetting PD_model( "./seeta_models/pd_2_00_pts5.dat", device, id );
    seeta::ModelSetting FR_model( "./seeta_models/fr_2_10.dat", device, id );
    //eng_p = new seeta::FaceEngine( FD_model, PD_model, FR_model, 2, 16 );
    eng_p = new seeta::FaceEngine( FD_model, PD_model, FR_model);

    if(eng_p == nullptr)
    {
         qDebug()<< "face engine init failed";
    }
#endif
    seeta::ModelSetting FD_model(FD_MODEL_PATH, device, id );
    seeta::ModelSetting PD_model(PD_MODEL_PATH, device, id );
    seeta::ModelSetting FR_model(FR_MODEL_PATH, device, id );
    //eng_p = new seeta::FaceEngine( FD_model, PD_model, FR_model, 2, 16 );
    m_eng = new seeta::FaceEngine( FD_model, PD_model, FR_model);

    m_eng->Load(FACE_DB_PATH);

    if(m_eng == nullptr)
    {
         qDebug()<< "face engine init failed....";
    }
    else
    {
        qDebug()<< "face engine init succeed!";
        //->Load(FACE_DB_PATH);
    }
}



FaceObject::~FaceObject()
{
    delete m_eng;
}

inline void set_seeta_img(SeetaImageData &s_img, unsigned char* dat, int w, int h, int chn)
{
    s_img.data = dat;
    s_img.width = w;
    s_img.height = h;
    s_img.channels = chn;
}

int FaceObject::register_face(cv::Mat &face_img)
{
#if 0 //调试
    Q_UNUSED(face_img);
    return 1;
#else
    //1. 先将OpenCV的图片格式转换为SeetaFace的图片格式
    SeetaImageData s_img;
    set_seeta_img(s_img, face_img.data,face_img.cols, face_img.rows, face_img.channels());

    //2. 然后用之进行检测
    int64_t face_id = m_eng->Register(s_img);
    if(face_id >= 0)//==-1为失败
    {
        //加入到数据库之中
        m_eng->Save(FACE_DB_PATH);
    }
    emit register_done(face_id);
    return face_id;
#endif
}

void FaceObject::query_face(cv::Mat &face_img)
{
#if 1
    SeetaImageData s_img;
    set_seeta_img(s_img, face_img.data,face_img.cols, face_img.rows, face_img.channels());

    float sim = 0;
    int64_t face_id = m_eng->Query(s_img,&sim);

    if(sim<0.3)//检查可信度，如果可信度太低，即使得到face_id,也将其设置为0
    {
        face_id = -1;//失败则返回-1
    }
#else
    int64_t face_id = 1;
    Q_UNUSED(face_img);
#endif
    emit query_done(face_id);
}

